package com.kly.manager.websocket.disruptor;

import cn.hutool.json.JSONUtil;
import com.kly.domain.entity.User;
import com.kly.manager.websocket.PictureEditHandler;
import com.kly.manager.websocket.enums.PictureEditMessageTypeEnum;
import com.kly.manager.websocket.model.PictureEditMessageRequest;
import com.kly.manager.websocket.model.PictureEditMessageResponse;
import com.kly.service.UserService;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * @author admin
 * @date 2025/3/21
 */
@Component
@Slf4j
public class PictureEditEventWorkHandler implements WorkHandler<PictureEditEvent> {

    @Resource
    private PictureEditHandler pictureEditHandler;

    @Resource
    private UserService userService;

    @Override
    public void onEvent(PictureEditEvent pictureEditEvent) throws Exception {
        //     获取信息
        WebSocketSession session = pictureEditEvent.getWebSocketSession();
        PictureEditMessageRequest pictureEditMessageRequest = pictureEditEvent.getPictureEditMessageRequest();
        PictureEditMessageTypeEnum pictureEditMessageTypeEnum = PictureEditMessageTypeEnum.getEnumByValue(pictureEditMessageRequest.getType());
        Long pictureId = pictureEditEvent.getPictureId();
        User user = pictureEditEvent.getUser();
        //     选择消息类型
        switch (pictureEditMessageTypeEnum) {
            case ENTER_EDIT:
                pictureEditHandler.handleEditEnterMessage(pictureId, user);
                break;
            case EXIT_EDIT:
                pictureEditHandler.handleEditExitMessage(pictureId, user);
                break;
            case EDIT_ACTION:
                pictureEditHandler.handleEditActionMessage(pictureEditMessageRequest, session, pictureId, user);
                break;
            default:
                PictureEditMessageResponse pictureEditMessageResponse = new PictureEditMessageResponse();
                // 错误消息类型
                pictureEditMessageResponse.setType(PictureEditMessageTypeEnum.ERROR.getValue());
                //         设置消息
                pictureEditMessageResponse.setMessage("消息类型错误");
                //        设置user
                pictureEditMessageResponse.setUserVO(userService.getUserVo(user));
                //         发送消息
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pictureEditMessageResponse)));

        }
    }
}
